import logging
import os
import sys
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler


def _reset_logger(log, file_name):
    for handler in log.handlers:
        handler.close()
        log.removeHandler(handler)
    log.handlers.clear()
    log.propagate = False

    # 控制台处理程序
    console_handle = logging.StreamHandler(sys.stdout)
    console_handle.setFormatter(
        logging.Formatter(
            "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )
    )

    # 文件处理程序，按天滚动
    base_file_name = os.path.basename(file_name)
    dir_name = os.path.dirname(file_name)

    file_handle = TimedRotatingFileHandler(os.path.join(dir_name, base_file_name), when='midnight', interval=1,
                                           backupCount=7, encoding="utf-8")
    file_handle.suffix = "%Y-%m-%d"

    # 自定义 namer 函数
    def custom_namer(name):
        return f"{datetime.strptime(name, '%Y-%m-%d').strftime('%Y-%m-%d')}-{base_file_name}"

    file_handle.namer = custom_namer
    file_handle.setFormatter(
        logging.Formatter(
            "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )
    )

    log.addHandler(file_handle)
    log.addHandler(console_handle)


def _get_logger(file_name):
    log = logging.getLogger(f"log_{file_name}")
    _reset_logger(log, file_name)
    log.setLevel(logging.INFO)
    return log


file_paths = ["bots/bot1/run_1.log", "bots/bot2/run_2.log", "bots/bot3/run_3.log", "bots/bot4/run_4.log",
              "bots/bot5/run_5.log"]

for file_path in file_paths:
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.exists(file_path):
        with open(file_path, 'w') as file:
            file.write('')

# 创建5个实例，每个实例都有自己的日志记录器
logger = _get_logger("run.log")

logger_1 = _get_logger("bots/bot1/run_1.log")
logger_2 = _get_logger("bots/bot2/run_2.log")
logger_3 = _get_logger("bots/bot3/run_3.log")
logger_4 = _get_logger("bots/bot4/run_4.log")
logger_5 = _get_logger("bots/bot5/run_5.log")

# 示例：记录日志
logger_1.info("This is an info message for Instance1.")
